#!/bin/bash

# Configuration variables
NODE_VERSION="v22.14.0"
NODE_DIST="node-${NODE_VERSION}-linux-x64"
NODE_TAR="${NODE_DIST}.tar.gz"
NODE_URL="https://registry.npmmirror.com/-/binary/node/latest-v22.x/${NODE_TAR}"
INSTALL_DIR="/usr/local/nodejs"
PROFILE_SCRIPT="/etc/profile.d/nodejs.sh"

# Function to check and install aria2c
check_and_install_aria2c() {
    if ! command -v aria2c &> /dev/null; then
        echo "⚠️ aria2c not installed, installing..."
        sudo apt-get update
        sudo apt-get install -y aria2
    else
        echo "✅ aria2c is already installed"
    fi
}

# Main installation process
echo "🚀 Starting installation of Node.js ${NODE_VERSION}..."

# Check for aria2c
check_and_install_aria2c

# Download Node.js
echo "📥 Downloading Node.js ${NODE_VERSION}..."
aria2c -x 16 -s 16 --allow-overwrite=true "${NODE_URL}" -o "${NODE_TAR}"

# Extract and install
echo "📦 Extracting and installing..."
sudo mkdir -p "${INSTALL_DIR}"
sudo tar -xzf "${NODE_TAR}" -C /usr/local
sudo rm -rf "${INSTALL_DIR}"
sudo mv "/usr/local/${NODE_DIST}" "${INSTALL_DIR}"

# Configure environment variables
echo "🛠️ Configuring environment variables..."
sudo tee "${PROFILE_SCRIPT}" > /dev/null <<EOF
#!/bin/bash
export PATH=${INSTALL_DIR}/bin:\$PATH
EOF
sudo chmod +x "${PROFILE_SCRIPT}"

# Apply environment variables
echo "🔄 Applying environment variables..."
source "${PROFILE_SCRIPT}"

# Verify installation
echo "✅ Verifying installation..."
if command -v node &> /dev/null && command -v npm &> /dev/null; then
    echo "Node.js version: $(node -v)"
    echo "npm version: $(npm -v)"
else
    echo "❌ Installation failed, please check the error messages"
    exit 1
fi

echo "🎉 Node.js ${NODE_VERSION} installation complete!"
